<template>
  <div :class="isCombineQuoteFee || newWindowFlag ? 'one-bill-wrap box-height' : 'one-bill-wrap'">
    <div :class="isCombineQuoteFee || newWindowFlag ? 'container w1200':'container'">
      <details-head v-model="status"
                    :title="`合单报价`"
                    :custom-list="buttonList"
                    :multiple="true"
                    :show-print="isCombineQuoteFee ? true : false"
                    :print-router="printPath"
                    :print-query="{combineId: value.combineId}"
                    :close-label="closeLabel"
                    :loading="loading"
                    @change="headChange" />
      <desc-list v-if="value.combineId"
                 :value="value"
                 :waybill-details="waybillDetails" />
      <icon-svg v-if="waybillDetails.price && waybillDetails.price.templateId"
                class-name="stampSty"
                icon-name="a-ziyuan4" />
      <layer title="合单子单">
        <child-list :table-data="tableData" />
      </layer>
      <layer title="费用信息">
        <div v-if="isCombineQuoteFee">
          <div class="cost-title">
            <div>合单报价<span>(单位：元)</span></div>
            <div>
              <el-button v-if="waybillDetails.price && waybillDetails.price.templateId"
                         type="text"
                         style="color: #000"
                         @click="matchVisible = true">查看合约信息 ></el-button>
            </div>
          </div>
          <el-table border
                    :data="oneBillFeeList">
            <template v-for="(item, index) in oneBillFeeColumn">
              <el-table-column :key="index"
                               :prop="item.name"
                               :label="item.label"
                               :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <div :class="['totalFee'].includes(item.name)?'totalSty':''">{{ scope.row[item.name] ? thousandDigit(scope.row[item.name], 2) : 0 }}
                  </div>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div v-if="computedQuto && !isCombineQuoteFee && (carrierExtraType != null || status === '3')">
          <transport-quote ref="transportQuote"
                           :key="keyQuto"
                           :current-status="status"
                           :edit-status="editStatus"
                           :data-list="quoteData"
                           :is-one-bill="true"
                           :carrier-extra-type="carrierExtraType"
                           :hide="value.hide"
                           @onTotal="handleQuoteTotal" />
        </div>
        <!-- 补充费用  -->
        <div v-if="computedQuto">
          <supplement-fee v-if="!isCombineQuoteFee && computedDriver"
                          :key="feeKey"
                          :dynamic-table="supplementFee"
                          :status="status"
                          :disabled="payDisabled"
                          :hide-status="hideStatus"
                          @addFee="handleAddFee"
                          @removeFee="handleRemoveFee"
                          @onTotal="handleQuoteTotal" />
        </div>
        <div v-if="!isCombineQuoteFee"
             class="fontSty1">
          {{computedDriver ? "报价费用+补充费用合计(含税费):" : "报价费用(含税费):" }}
          <span class="fontSty2">{{ totalFee }}</span>
        </div>
        <el-input v-if="!isCombineQuoteFee && computedDriver"
                  v-model="remarks"
                  type="textarea"
                  :rows="4"
                  :disabled="remarksDisabled"
                  maxlength="200"
                  placeholder="请输入备注说明"></el-input>
        <pay-type ref="payType"
                  :key="payKey"
                  :arrive-pay-fee-disabled="arrivePayFeeFlag"
                  :collection-fee-disabled="collectionFeeFlag"
                  :prepay-fee-disabled="prepayFeeFlag"
                  :waybill-price="waybillDetails && waybillDetails.price"
                  :data-list="isCombineQuoteFee? oneBillFeeList : payList"
                  :disabled="payDisabled || isCombineQuoteFee"
                  :is-one-bill="true" />
      </layer>
      <layer v-show="isTrack"
             title="跟踪信息">
        <Information :value="track" />
      </layer>
      <quote-matching-detail v-if="matchVisible"
                             :match-id="matchId"
                             :table-column="wayBillColumn"
                             :list-data="priceList"
                             :match-visible.sync="matchVisible"
                             :surcharge-fees="surchargeFees"
                             v-bind="$attrs" />
    </div>
  </div>
</template>

<script>
import QuoteMatchingDetail from "../transport/components/QuoteMatchingDetail.vue"
import DetailsHead from "@components/detailsHead/Header.vue";
import DescList from "./components/DescList";
import Layer from "@/components/detailsLayer/Layer";
import ChildList from "./components/ChildList.vue";
import TransportQuote from "../transport/components/TransportQuote.vue";
import SupplementFee from "../transport/components/SupplementFee.vue";
import PayType from "../transport/components/PayType.vue";
// import Bargain from '../transport/components/Bargain.vue'
import { onebill, track } from "@/api/index";
import Information from "@/components/track/Information.vue";
import { returnThousandDigit, floatAdd } from "@/libs/util.js";
import completeData from "@/libs/conversion.js";
import quotation from "@/api/modules/quotation";
import { revoke, agree, reject, totalFee } from "./components/scheduler";
import { mapState } from "vuex";

export default {
  name: "OneBillQuote",
  components: {
    DetailsHead,
    Layer,
    ChildList,
    TransportQuote,
    PayType,
    SupplementFee,
    DescList,
    Information,
    QuoteMatchingDetail
  },
  data () {
    return {
      waybillDetails: {},
      fromDetails: {},
      tableData: [],
      fromData: {},
      remarks: null, // 备注
      quoteTotal: 0, //合单费用合计
      bargainTotal: 0, //补充费用合计
      totalFee: 0, //总合计
      loading: false,
      timer: null,
      quoteData: [], // 报价费用
      supplementFee: [], // 补充费用
      payList: [], // 预付款
      keyQuto: 1,
      payKey: 2,
      feeKey: 3,
      oneBillFeeList: [], // 合单费用
      track: [], // 跟踪信息
      isTrack: false, // 跟踪信息标题显示
      carrierExtraType: null, // 是否是个体司机,
      surcharge: null,      // 区分按单合补充
      matchVisible: false,
      wayBillColumn: [
        { label: "合单运费", name: "wholeFee", },
        { label: "装货", name: "loadFee" },
        { label: "卸货", name: "unloadFee" },
        { label: "保险", name: "insureFee" },
        { label: "税费", name: "taxFee" }
      ],
      oneBillFeeColumn: [
        { label: "合单运费", name: "wholeFee" },
        { label: "装货费", name: "loadFee" },
        { label: "卸货费", name: "unloadFee" },
        { label: "保险费", name: "insureFee" },
      ],
      priceList: [],
      matchId: null,
      // 不可编辑状态：议价 补充报价 审核报价 议价 已关闭
      inhibitInputStatus: ["1", "2", "11", "18", "32", "14"]
    };
  },
  computed: {
    ...mapState({
      tenantInfo: (state) => state.tenant.tenantInfo
    }),
    /* 合单组件传值异步处理 */
    computedQuto () {
      return this.surcharge != null || this.status === '10'
    },
    computedDriver () {
      /* 是个体司机的按单报价 不会有补充费用 和备注  代收货款 */
      /* 个体司机按单报价的时候不要显示新增费用按钮，补充报价的时候要显示    && this.status != '2'*/
      const isIndividualDriver = this.carrierExtraType && !this.surcharge && this.status !== '2';
      /* isIndividualDriver ? 个体司机按单报价 : 补充报价 */
      const disabled = isIndividualDriver ? false : true;
      return disabled;
    },
    value () {
      return this.$route.query
    },
    status () {
      return this.$route.query?.status?.toString()
    },
    closeLabel () {
      return this.isCombineQuoteFee || this.newWindowFlag ? '关闭' : '返回'
    },
    /* 合单报价 */
    editStatus () {
      const { status, value, surcharge, inhibitInputStatus } = this;
      const statusMap = {
        "3": ["3"],
        "11": (!value?.hide || surcharge) ? ["11"] : [],
        "8": (!value?.hide || surcharge) ? ["8"] : [],
      };

      return statusMap[status] || inhibitInputStatus;
    },
    // 新增费用按钮
    hideStatus () {
      if (!this.surcharge && this.value.customerId) {
        return ["1", "11", "8"];
      } else if (this.status === '8' && !this.value.hide) {
        return ["8"];
      } else {
        return ["11", "1", "32", "14", "18"];
      }
    },
    /* 付款方式 */
    payDisabled () {
      if (["1", "32", "14", "18"].includes(this.status) || (['8', '11'].includes(this.status) && !this.value.hide)) {
        return true;
      }
      return false;
    },
    /* 备注 */
    remarksDisabled () {
      if (this.inhibitInputStatus.includes(this.status) || (this.status === "8" && !this.value.hide) || this.surcharge) {
        return true;
      }
      return false;
    },
    /* contractNo->是否从合同编号进入  currentStatus->状态  */
    btnDetailsTranslate () {
      return (contractNo, currentStatus) => {
        if (contractNo) {
          let statusMap = new Map([
            [
              '11',
              [
                { label: "同意", status: "agree" },
                { label: "拒绝", status: "refuse" },
                { label: "议价", status: "routerBargain" }
              ]
            ],
            [
              '10',
              [
                { label: "保存", status: "create" },
                { label: "发送", status: "send" }
              ]
            ],
            ['1', [{ label: "撤回", status: "revoke" }]],
            ['2', [{ label: "发送", status: "fillBargain" }]],
            [
              '8',
              [
                { label: "同意", status: "agree" },
                { label: "议价", status: "routerBargain" }
              ]
            ],
            [
              '0',
              [
                { label: "保存", status: "update" },
                { label: "发送", status: "send" },
                { label: "关闭", status: "close" },
              ]
            ]
          ]);
          return statusMap.get(currentStatus);
        } else {
          let statusMap = new Map([
            [
              '10',
              [
                { label: "保存", status: "create" },
                { label: "发送", status: "send" }
              ]
            ],
            ['1', [{ label: "撤回", status: "revoke" }]],
            ['2', [{ label: "发送", status: "fillBargain" }]],
            [
              '0',
              [
                { label: "保存", status: "update" },
                { label: "发送", status: "send" },
                { label: "关闭", status: "close" },
              ]
            ],
            ["default", [{ label: "发送", status: "bargain" }]]
          ]);
          return statusMap.get(currentStatus) || statusMap.get("default");
        }
      };
    },
    /* 后期优化逻辑 */
    buttonList () {
      /* surcharge true为被拒绝补充报价  false为被拒绝按单报价 */
      let btnList
      if (this.status === '3') {
        if (this.surcharge) {
          btnList = [{ label: "发送", status: "send" }]
        } else {
          btnList = [{ label: "保存", status: "update" }, { label: "发送", status: "send" }, { label: "关闭", status: "close" },]
        }
      } else {
        btnList = this.btnDetailsTranslate(
          this.value.contractNo || null,
          this.status
        );
      }
      return btnList;
    },
    /* 第一次报价 或者 审核报价通过的标识*/
    supplementOffer () {
      return this.$route.query.carrierId;
    },
    /* 是否为合单费用途径进入 */
    isCombineQuoteFee () {
      return this.$route.query?.isCombineQuoteFee ? true : false
    },
    newWindowFlag () {
      return ["32", "14"].includes(this.status)
    },
    // 合单的第一个子单
    fristChildWaybill () {
      return this.waybillDetails.waybills && this.waybillDetails.waybills[0]
    },
    arrivePayFeeFlag () {
      return this.fristChildWaybill?.finance?.arrivePayFeeFlag;
    },
    collectionFeeFlag () {
      return this.fristChildWaybill?.finance?.collectionFeeFlag;
    },
    prepayFeeFlag () {
      return this.fristChildWaybill?.finance?.prepayFeeFlag;
    },
    printTemplate () {
      return this.tenantInfo?.config?.printTemplate || [];
    },
    // 有效打印路由
    effectivePaths () {
      return ['CombineFeePrint'];
    },
    // 租户配置打印路由
    printPath () {
      const cstPrintName = 'customerCombineFeeTemplate';
      const carrPrintName = 'carrierCombineFeeTemplate';
      let path = null;
      let printName = this.waybillDetails?.waybills && this.waybillDetails?.waybills[0]?.waybillType === 10 ? cstPrintName : carrPrintName;
      this.printTemplate?.length && this.printTemplate.some((o) =>
        (path = printName === o.name ? o.value.split(";") : null)
      );
      if (path && path.length) {
        return this.effectivePaths.includes(path[0]) ? path[0] : 'CombineFeePrint'
      }
      return 'CombineFeePrint';
    },
  },
  created () {
    this.getCombineDetail();
    if (this.value.quotationId) {
      this.getQuotation();
    }
    this.trackInformation();
  },
  // 清除定时器
  beforeDestroy () {
    this.$once("hook:beforeDestroy", () => {
      clearInterval(this.timer);
    });
  },
  methods: {
    thousandDigit (value, digit) {
      return returnThousandDigit(value, digit)
    },
    // 获取合单详情
    async getCombineDetail () {
      let { data } = await onebill.getCombineDetail(this.value.combineId);
      let { waybills } = data;
      this.waybillDetails = data;
      this.waybillDetails.orderSubQuantity = waybills?.length;
      this.tableData = completeData.redirect(waybills);
      this.total = waybills?.length;
      this.carrierExtraType = data.carrier?.carrierExtraType;
      console.log('carrierExtraType 字段为1是个体司机---为0不是个体司机', this.carrierExtraType)
      if (!data.carrier?.carrierExtraType) {
        this.oneBillFeeColumn.push(
          { label: "提货费", name: "pickFee" },
          { label: "送货费", name: "deliverFee" },
          { label: "税费", name: "taxFee" },
        )
      }

      if (data?.price?.minCost) {
        this.oneBillFeeColumn.push(
          { label: "最低费用", name: "minCost" },
        )
      }
      this.oneBillFeeColumn.push(
        { label: "补充费用", name: "surchargeFee" },
        { label: "总费用", name: "totalFee" }
      )
      this.oneBillFeeList = data?.price ? [{ ...data?.price }] : [{}];
      if (data?.price?.quotationStatus && this.isCombineQuoteFee) {
        this.getQuoteDetail();
      }
    },
    // 获取有效报价详情
    async getQuoteDetail () {
      let { data } = await quotation.getValidCombineQuotation(this.value.combineId);
      if (data) {
        this.quoteDetail = data
        // 运单费用初始值
        this.priceList = [{
          wholeFee: data?.transportFee || 0, //合单费用
          pickFee: data?.pickFee || 0, //提货费
          deliverFee: data?.deliverFee || 0, //送货费
          loadFee: data?.loadFee || 0, //装货费
          unloadFee: data?.unloadFee || 0, //卸货费
          insureFee: data?.insureFee || 0, //保险费
          taxFee: data?.taxFee || 0, // 税费
          minCost: data?.minimumFee || 0 //最低费用
        }];
        if (this.waybillDetails.price.templateId) {
          this.matchId = data.matchId
          this.surchargeFees = data?.surchargeFees || []
        }
        let quoteTotal = 0;
        if (data?.minimumFee) {
          this.wayBillColumn.push({ label: "最低费用", name: "minCost" });
          quoteTotal = data.minimumFee + data?.taxFee || 0 + data?.insureFee || 0
        } else {
          // 计算运单费用总和
          for (let key in this.priceList[0]) {
            quoteTotal += this.priceList[0][key];
          }
        }
        this.priceList[0].quoteTotal = quoteTotal;
        // 补充费用
        let bargainTotal = 0;
        this.bargainList = data?.surchargeFees || [];
        this.bargainList.forEach((element) => {
          bargainTotal += element.money || 0;
        });
        // 付款方式
        this.payList = [{ ...data }];
        this.totalFee = returnThousandDigit(quoteTotal + bargainTotal, 2);
        this.wayBillColumn.push({ label: "报价费用", name: "quoteTotal" });
      }
    },
    // 合单报价费用合计
    handleQuoteTotal (type, val) {
      this.quoteTotal = type === 1 ? val : this.quoteTotal;
      this.bargainTotal = type === 2 ? val : this.bargainTotal;
      this.totalFee = returnThousandDigit(
        Number(this.quoteTotal) + Number(this.bargainTotal),
        2
      );
    },
    // 触发事件
    headChange (status) {
      let transportQuoteList = this.$refs.transportQuote.tableData;
      let payTypeData = this.$refs.payType.tableData;
      /* 补充费用 */
      this.fromData = {
        remarks: this.remarks,
        subjectId: this.value.subjectId,
        quotationId: this.value.quotationId,
        orderNo: this.waybillDetails.no,
        ...transportQuoteList[0],
        ...payTypeData[0]
      };
      this.fromData.surchargeFees = this.supplementFee?.length && this.supplementFee.filter(x => {
        if (x.type && x.money) {
          return x
        }
      });
      this.fromData.surchargeFees = this.fromData.surchargeFees || []
      let childType = this.supplementFee.find(x => (!x.type || x.type === '') && (!x.typeName || x.typeName === ''));
      let child = this.supplementFee.find(x => x.type && ((!x.money || x.money === '') && x.money !== 0));
      if (childType) {
        return this.$message.warning("请选择费用类型");
      }
      if (child) {
        return this.$message.warning("补充费用不能为空");
      }
      this.action(status);
    },
    // 关闭
    handelClose () {
      this.$router.back();
      // window.close();
    },
    /* 创建 */
    create () {
      let create = new Promise(async (resolve, reject) => {
        let response = await quotation.createQuotation(this.fromData);
        let { data } = response;
        return resolve(data);
      });
      return create;
    },
    /* 更新 */
    update () {
      let update = new Promise(async (resolve, reject) => {
        let response = await quotation.updateQuotation(
          this.value.quotationId,
          this.fromData
        );
        let { data } = response;
        return resolve(data);
      });
      return update;
    },
    /* 发送 */
    send (params) {
      let send = new Promise(async (resolve, reject) => {
        let response = await quotation.sendQuotation(params);
        return resolve(response);
      });
      return send;
    },
    // 保存 发送
    submit (diff) {
      if (diff === "create") {
        this.create();
        this.callback();
      } else if (diff === "update") {
        this.update();
        this.callback();
      } else if (diff === "send" && !['0', '3'].includes(this.status)) {
        /* 创建发送 */
        this.create().then((_o) => {
          let { quotationId } = _o;
          this.send({ quotationId: quotationId }).then((_s) => {
            this.callback();
          });
        });
      }

      if (diff === "send" && ['0', '3'].includes(this.status)) {
        if (this.surcharge) {
          const { surchargeFees } = this.fromData
          /* 过滤已通过补充报价的数据 */
          const filterSurchargeFees = surchargeFees.filter(({ typeDisabled }) => !typeDisabled)
          const data = { ...this.fromData, submit: true, surchargeFees: filterSurchargeFees }
          quotation.addSurcharge(data).then((res) => {
            if (res.code != 0) return;
            this.callback();
          });
        } else {
          this.update().then((_o) => {
            let { quotationId } = _o;
            this.send({ quotationId: quotationId }).then((_s) => {
              if (_s.code != 0) return;
              this.callback();
            });
          });
        }
      }
    },
    /* 议价 */
    async getBargain () {
      let quotationId = this.value.quotationId;
      /* 区分通过的和补充的费用 */
      this.fromData.surchargeFees = this.fromData?.surchargeFees.filter(
        (x) => !x.typeDisabled
      );
      let params = { quotationId, ...this.fromData, method: this.surcharge ? 'SURCHARGE' : 'STANDARD' };
      /* 付款方式清空补0 */
      if (!this.fromData.arrivePayFee) {
        this.fromData.arrivePayFee = 0;
      }
      if (!this.fromData.prepayFee) {
        this.fromData.prepayFee = 0;
      }
      let response = await quotation.bargain(params);
      this.callback();
    },
    /* 补充报价 */
    async getFillBargain () {
      let quotationId = this.value.quotationId;
      /* 区分通过的和补充的费用 */
      this.fromData.surchargeFees = this.fromData?.surchargeFees.filter(
        (x) => !x.typeDisabled
      );
      /* 付款方式清空补0 */
      if (!this.fromData.arrivePayFee) {
        this.fromData.arrivePayFee = 0;
      }
      if (!this.fromData.prepayFee) {
        this.fromData.prepayFee = 0;
      }
      let params = { quotationId, ...{ submit: true }, ...this.fromData };
      if (!this.fromData.surchargeFees.length &&
        this.fromData.arrivePayFee === Number(this.fromDetails.arrivePayFee) &&
        this.fromData.prepayFee === Number(this.fromDetails.prepayFee)) {
        return this.$message.warning("您还未输入报价信息，请检查输入的值");
      }
      if (this.fromData.surchargeFees.length && !this.fromData.surchargeFees[0].money) {
        return this.$message.warning("您还未输入报价信息，请检查输入的值");
      }
      let response = await quotation.addSurcharge(params);
      this.callback();
    },
    /* 查询报价详情 */
    async getQuotation () {
      let { data } = await quotation.getQuotation(this.value.quotationId);
      let {
        transportFee,
        transportFeeBefore,
        loadFee,
        loadFeeBefore,
        unloadFee,
        unloadFeeBefore,
        insureFee,
        insureFeeBefore,
        taxFee,
        taxFeeBefore,
        pickFee,
        pickFeeBefore,
        deliverFee,
        deliverFeeBefore,
        prepayFee,
        arrivePayFee,
        remarks,
        minimumFee,
        surcharge,
        ...params
      } = data;
      this.surcharge = surcharge
      console.log('surcharge 字段为true是补充报价---为false是按单报价', surcharge)
      this.fromDetails = data;
      /* 报价费用总数 */
      const fees = [transportFee, loadFee, unloadFee, insureFee, pickFee, deliverFee, taxFee];
      this.quoteTotal = totalFee({ minimumFee, taxFee, insureFee, fees })

      /* 补充费用合计 */
      let feeTotalList = [];
      if (
        params?.surchargeFees?.length &&
        !params?.rejectedFees &&
        !params?.auditingFees &&
        !params?.bargainFees &&
        !params?.closedFees
      ) {
        /* 第一次报价 或者 审核报价通过 */
        if (this.supplementOffer) {
          params?.surchargeFees.forEach((item) => {
            if (this.supplementOffer) {
              item.typeDisabled = true;
            }
          });
        } else {
          params?.surchargeFees.forEach((item) => {
            if (this.status != 0) {
              item.barginDisabled = true;
            }
          });
        }
        /* 第一次报价 或者 审核报价通过 */
        params?.surchargeFees.forEach(item => {
          if (this.status != 0) {
            item.barginDisabled = true
          } else if (this.supplementOffer) {
            item.typeDisabled = true
          }
        })
        feeTotalList = [...params?.surchargeFees];
      } else if (params?.rejectedFees && ['3'].includes(this.status)) {
        /* 被拒绝费用 */
        params?.surchargeFees.forEach((item) => {
          item.typeDisabled = true;
        });
        feeTotalList = [
          ...params?.surchargeFees,
          { title: "被拒绝", typeDisabled: true, typeName: "【被拒绝】" },
          ...params?.rejectedFees
        ];
      } else if (
        params?.auditingFees &&
        (this.status === "1" || this.status === "11")
      ) {
        // feeTotalList = auditingFeesStrategy({ data: params })
        /* 待审核费用 */
        params?.surchargeFees.forEach((item) => {
          item.typeDisabled = true;
        });
        // 待审核的补充费用明细 
        if (this.surcharge) {
          params?.auditingFees.forEach(item => {
            item.typeDisabled = false
            item.barginDisabled = true
            item.disabled = true
          })
        }

        feeTotalList = [
          ...params?.surchargeFees,
          { title: "待审核", typeDisabled: true, typeName: "【待审核】" },
          ...params?.auditingFees
        ];
      } else if (params?.bargainFees && ['1', '8', '18'].includes(this.status)) {
        /* 议价费用  发起方*/
        if (params?.surchargeFees?.length) {
          params?.surchargeFees.forEach((item) => {
            item.typeDisabled = true;
          });
          feeTotalList = [
            ...params?.surchargeFees,
            { title: "议价", typeDisabled: true, typeName: "【议价】" },
            ...params?.bargainFees
          ];
        } else {
          feeTotalList = [...params?.bargainFees];
        }
      } else if (params?.bargainFees && this.status === "11") {
        /* 待审核费用 */
        if (params?.surchargeFees?.length) {
          params?.surchargeFees.forEach((item) => item.typeDisabled = true);

          // 议价的补充费用明细 
          if (this.surcharge) {
            params?.bargainFees.forEach(item => {
              item.typeDisabled = false
              item.barginDisabled = true
              item.disabled = true
            })
          }
          feeTotalList = [
            ...params?.surchargeFees,
            { title: "待审核", typeDisabled: true, typeName: "【待审核】" },
            ...params?.bargainFees
          ];
        } else {
          feeTotalList = [...params?.bargainFees];
        }
      } else if (params?.closedFees && ["32", "14"].includes(this.status)) {
        if (params?.surchargeFees?.length) {
          params?.surchargeFees.forEach((item) => item.typeDisabled = true);

          // 已关闭补充费用明细 
          if (this.surcharge) {
            params?.closedFees.forEach(item => {
              item.typeDisabled = false
              item.barginDisabled = true
              item.disabled = true
            })
          }
          feeTotalList = [
            ...params?.surchargeFees,
            { title: "已关闭", typeDisabled: true, typeName: "【已关闭】" },
            ...params?.closedFees
          ];
        } else {
          feeTotalList = [...params?.closedFees];
        }
      }

      feeTotalList.forEach((fee) => {
        if (this.status === "2") {
          fee.disabled = false;
          fee.typeDisabled = true
          fee.barginDisabled = false
          fee.status = "2";
        }
        // 审核报价按单议价费用项
        else if (this.status === "11" && !params?.rejectedFees && !params?.auditingFees && !params?.bargainFees) {
          fee.typeDisabled = false
          fee.barginDisabled = true
          fee.disabled = true;
        }
        this.bargainTotal += fee.money || 0;
      });

      /* 补充费用 */
      this.supplementFee = feeTotalList;
      // 运单+补充费用的合计
      this.totalFee = returnThousandDigit(
        floatAdd(this.quoteTotal, this.bargainTotal),
        2
      );
      /* 费用信息 - 合单报价 */
      this.$set(this.quoteData, 0, {
        transportFee: transportFee || 0,
        transportFeeBefore: transportFeeBefore || 0,
        loadFee: loadFee || 0,
        loadFeeBefore: loadFeeBefore || 0,
        unloadFee: unloadFee || 0,
        unloadFeeBefore: unloadFeeBefore || 0,
        insureFee: insureFee || 0,
        insureFeeBefore: insureFeeBefore || 0,
        taxFee: taxFee || 0,
        taxFeeBefore: taxFeeBefore || 0,
        pickFee: pickFee || 0,
        pickFeeBefore: pickFeeBefore || 0,
        deliverFee: deliverFee || 0,
        deliverFeeBefore: deliverFeeBefore || 0,
        minimumFee: minimumFee || 0,
        quoteTotal: this.quoteTotal
      });
      /* 预付款 和 货到付款*/
      this.$set(this.payList, 0, {
        prepayFee: prepayFee,
        arrivePayFee: arrivePayFee
      });
      /* 备注 */
      this.remarks = remarks;
    },
    routerLink () {
      if (!this.waybillDetails?.price) {
        this.$message.warning("暂无报价！")
        return false
      }
      const { href } = this.$router.resolve({
        name: `oneBillQuoteWindow`,
        query: {
          combineId: this.value.combineId,
          status: this.status,
          contractNo: this.value.contractNo,
          carrierId: this.waybillDetails?.carrier?.carrierId,
          isCombineQuoteFee: 1,
        }
      });
      window.open(href, "_blank");
    },
    // 操作回调
    callback () {
      this.loading = true;
      this.$message.success("操作成功");
      this.timer = setTimeout(() => {
        this.loading = false;
        this.handelClose();
      }, 1000);
    },
    /* 操作按钮 */
    action (status) {
      let submitStatus = ["create", "send", "update"];
      if (submitStatus.includes(status)) {
        /* 合单报价提示 */
        let onOffer = this.$refs.transportQuote.tableData.filter(
          (o) => o.quoteTotal
        );
        if (!onOffer.length)
          return this.$message.warning("请至少填写一项报价费用");
        /* 补充费用提示 */
        /* 保存  发送 */
        this.submit(status);
      } else if (status === "bargain") {
        /* 议价 */
        this.getBargain();
      } else if (status === "fillBargain") {
        /* 补充议价 */
        this.getFillBargain();
      } else if (status === "revoke") {
        /* 撤回 */
        this.$nextTick(() => {
          revoke(this.fromDetails);
          // this.callback()
        });
      } else if (status === "agree") {
        /* 同意 */
        this.$nextTick(() => {
          agree(this.fromDetails);
          // this.callback()
        });
      } else if (status === "refuse") {
        /* 拒绝 */
        this.$nextTick(() => {
          reject(this.fromDetails);
          // this.callback()
        });
      } else if (status === "routerBargain") {
        /* 审核报价 按单报价  合单报价编辑 */
        this.$nextTick(() => {
          this.$router.push({
            path: "oneBillQuote",
            query: {
              combineId: this.value.combineId,
              contractNo: this.fromDetails.contractNo,
              quotationId: this.fromDetails.quotationId,
              status: this.status,
              hide: true
            }
          });
          /* 审核报价-》议价页面 不可以 修改 按单报价的数据 */
          if (!this.surcharge) {
            this.keyQuto++;
          }
          this.payKey++;
        });
      } else if (status === "close") {
        this.$confirm("确认关闭报价单？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.closeRes();
        });
      }
    },
    // 关闭报价单
    async closeRes () {
      await quotation.discard({ quotationId: this.value.quotationId, surcharge: this.fromDetails?.hasSurcharge });
      this.handelClose();
    },
    // 跟踪信息
    async trackInformation () {
      let id = this.value?.quotationId
      let type = 'quotation'
      if (id) {
        let { code, data } = await track.information(id, type);
        if (code === 0 && data.length) {
          data.map(item => {
            if (item.message.indexOf('，') != -1 && item.message.lastIndexOf('】')) {
              item.timestamp = item.message.slice(0, item.message.indexOf('，'))
              item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
              item.content = item.message.includes('】') ? item.message.slice(item.message.lastIndexOf('】') + 1) : item.message.slice(item.message.indexOf('，') + 1)
            }
          })
          this.track = data
          this.isTrack = true
        }
      }
    },
    // 新增费用项
    handleAddFee () {
      const feeRow = { money: "", type: "", typeName: "", typeDisabled: "", remarks: "", total: "" }
      this.supplementFee.push(feeRow);
    },
    handleRemoveFee (index, row) {
      this.supplementFee.splice(index, 1)
      console.log('row', row)
    }
  },
};
</script>

<style lang="scss" scoped>
.one-bill-wrap {
  height: calc(100vh - 80px);
  overflow-x: hidden;
  overflow-y: scroll;
}
.box-height {
  height: calc(100vh) !important;
}
.container {
  background: var(--prev-bg-white);
  margin: 0 auto;
  position: relative;
}
.w1200 {
  width: 1200px;
}
.mb20 {
  margin-bottom: 20px;
}
.fontSty1 {
  color: var(--prev-color-text-ashes);
  display: flex;
  justify-content: flex-end;
  height: 40px;
  line-height: 40px;
}
.fontSty2 {
  color: var(--prev-color-primary);
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}
.cost-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  font-size: 16px;
  span {
    color: var(--prev-border-color-grey);
    font-size: 12px;
  }
  .el-button {
    font-size: 16px;
  }
}
.ml8 {
  margin-left: 8px;
}
.totalSty {
  color: var(--prev-color-primary) !important;
}
.stampSty {
  width: 126px;
  height: 126px;
  position: absolute;
  left: 75%;
  top: 13%;
}
</style>
